package com.example.demo;

import com.google.gson.Gson;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class AppTest {
    public static void main(String[] arg) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0);
//        server.createContext("/post", new BasicPostHttpHandler());
        server.createContext("/", new BasicPostHttpHandler());
        // default excutor
        server.setExecutor(null);
        server.start();
    }

    /**
     * http://localhost:8001/post
     */
    public static class BasicPostHttpHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {

            InputStream is = httpExchange.getRequestBody();

            String requestData = is2string(is);
            System.out.println("request: " + requestData);
//            String response = "{\"pid\":\"510229197206267348\",\"pname\":\"张三\"}";   // 写回这个数据就会failed
//             String response = "hello world";  // 若写回这个数据则没有问题
//            String response = "{'hello':'world'}";  // 若写回这个数据则没有问题
            HashMap map = new HashMap<>();
            map.put("test", 1);
            map.put("aaaa", 2);
            Gson gson = new Gson();
            String response = gson.toJson(map); // 若写回这个数据则没有问题
            System.out.println("response: " + response);
//            is.close();

            Headers headers = httpExchange.getResponseHeaders();
            headers.set("Content-Type", "application/json; charset=utf-8");
            headers.set("Access-Control-Allow-Origin", "*");
            headers.set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
            headers.set("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");

            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes(StandardCharsets.UTF_8));
            os.close();
        }

        private String is2string(InputStream is) throws IOException {
            final int bufferSize = 1024;
            final char[] buffer = new char[bufferSize];
            final StringBuilder out = new StringBuilder();
            Reader in = new InputStreamReader(is, "UTF-8");

            for (; ; ) {
                int rsz = in.read(buffer, 0, buffer.length);
                if (rsz < 0)
                    break;
                out.append(buffer, 0, rsz);
            }
            return out.toString();
        }

    }

}
